package com.coderman.tianhua.idgenerator.core.service.rule;

import com.coderman.tianhua.idgenerator.common.bean.SequenceRule;
import com.coderman.tianhua.idgenerator.common.enums.Status;
import com.coderman.tianhua.idgenerator.common.service.SequenceRepository;
import com.coderman.tianhua.idgenerator.common.thread.ServiceThread;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 运行时规则定义缓存
 *
 * @author haozi
 * @date 2019-11-0811:45
 */
@Slf4j
@Component(value = "sequenceRuleCache")
public class SequenceRuleCache extends ServiceThread {
    //30秒
    private final static Long WAIT_INTERVAL = 30000L;

    //配置信息缓存
    private Map<String, SequenceRule> sequenceRuleDefinitionCache = null;

    @Autowired
    private SequenceRepository sequenceRepository;

    public SequenceRuleCache() {
        //load();
    }

    public SequenceRule get(String key) {
        return sequenceRuleDefinitionCache.get(key);
    }

    public void load() {
        sequenceRuleDefinitionCache = sequenceRepository.getRuleByStatus(Status.RUNNING)
                .stream()
                .collect(Collectors.toMap(SequenceRule::getKey, sequenceRule -> sequenceRule));
    }

    public Collection<SequenceRule> getAllRule() {
        return sequenceRuleDefinitionCache.values();
    }

    @Override
    public String getServiceName() {
        return "Sequence-Rule-Thread";
    }

    @Override
    public void run() {
        log.info(this.getServiceName() + " service started");

        while (!this.isStopped()) {
            this.waitForRunning(WAIT_INTERVAL);
            this.load();
        }

        log.info(this.getServiceName() + " service end");
    }
}
